package cn.shenlong.portal.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.shenlong.common.Page;
import cn.shenlong.common.Pagination;
import cn.shenlong.portal.domain.Member;
import cn.shenlong.portal.domain.MemberCard;
import cn.shenlong.portal.mapper.MemberMapper;
import cn.shenlong.portal.service.MemberCardService;
import cn.shenlong.portal.service.MemberService;

@Service("MemberService")
public class MemberServiceImpl implements MemberService {

	@Autowired
	private MemberMapper MemberMapper;
	
	@Autowired
	private MemberCardService memberCardService;
	
	@Override
	@Transactional
	public void save(Member member,long memberId) {
		MemberMapper.saveEntity(member);
	}

	@Override
	public Pagination findMember(Member member, Map<String, Object> otherParm,Integer pageSize, Integer pageNo) {
		Pagination p = new Pagination();
		List<Member> contentList= MemberMapper.findPageListByCriteria(initmemberParm(member,otherParm), initRowBounds(pageSize, pageNo, p));
		Long count = MemberMapper.findCountByCriteria(initmemberParm(member,otherParm));
		p.setList(contentList);
		p.setTotalCount(count.intValue());
		return p;
	}
	
	@Override
	public Page<Member> findPageByParm(Map<String, Object> otherParm, Integer pageNo, Integer pageSize) {
		Page<Member> p = new Page<Member>();
		List<Member> eventList = MemberMapper.findPageListByCriteria(otherParm, initRowBounds(pageSize, pageNo, p));
		Long count = MemberMapper.findCountByCriteria(otherParm);
		p.setList(eventList);
		p.setTotalCount(count.intValue());
		return p;
	}
	
	private RowBounds initRowBounds(Integer pageSize, Integer pageNo, Page p) {
		RowBounds rowBounds = null;
		if (pageSize == null || pageNo == null) {
			rowBounds = new RowBounds();
		} else {
			p.setPageNo(pageNo);
			p.setPageSize(pageSize);
			rowBounds = new RowBounds(p.getFirstResult(), p.getPageSize());
		}
		return rowBounds;
	}
	
	private Map<String,Object> initmemberParm(Member member,Map<String,Object> otherParm){
		Map<String,Object> parm = new HashMap<String, Object>();
		if(otherParm!=null){
			parm.putAll(otherParm);
		}
		if(member==null){
			return parm;
		}else{
			parm.put("memberId", member.getMemberId());
			parm.put("loginName", member.getLoginName());
		    parm.put("email", member.getEmail());
		    parm.put("password", member.getPassword());
		    parm.put("dataflg", member.getDataflg());
		    
		    //其他预留字段暂时不去管他
		    /*parm.put("address", member.getAddress());
		    parm.put("telephone", member.getTelephone());
		    parm.put("description", member.getDescription());
		    parm.put("remark", member.getRemark());
		    parm.put("imgUrl", member.getImgUrl());*/
			return parm;
		}

	}
    private RowBounds initRowBounds(Integer pageSize, Integer pageNo, Pagination p) {
        RowBounds rowBounds = null;
        if (pageSize == null || pageNo == null) {
            rowBounds = new RowBounds();
        } else {
            p.setPageNo(pageNo);
            p.setPageSize(pageSize);
            rowBounds = new RowBounds(p.getFirstResult(), p.getPageSize());
        }
        return rowBounds;
    }

	@Override
	public Member findMemberByMemberId(long memberId) {
		return MemberMapper.findByPK(memberId);
	}

	@Override
	public Member updateMember(Member member) {
		 int i = MemberMapper.updateEntity(member);
		 if(i<0) return null;
		 return MemberMapper.findByPK(member.getMemberId());
	}

	@Override
	public void deleteMember(Long[] memberId) {
		MemberMapper.deleteByPKArray(memberId);
	}

	@Override
	public void deleteByMemberId(List<Long> MemberId) {
		MemberMapper.deleteByPKArray((Long[])MemberId.toArray());
	}
	
	public void save(Member member){
		MemberMapper.saveEntity(member);
	}

	/**
	 * 会员登录，返回会员对象
	 * @param loginName 登录名
	 * @param password 密码
	 * @return 会员对象
	 */
	public Member login(String loginName, String password) {
		return MemberMapper.login(loginName, password);
	}
	
	/**
	 * 根据登录名查询会员数量，防止注册时出现重复的用户
	 * @param loginName 登录名
	 * @return
	 */
	public Long findMemberCountByName(String loginName) {
		return MemberMapper.findMemberCountByName(loginName);
	}
	
	/**
	 * 验证邮箱是否存在
	 * @param email 邮箱
	 * @return
	 */
	public Member findByEmail(String email) {
		return MemberMapper.findByEmail(email);
	}
	
	/**
	 * 验证邮箱是否存在
	 * @param email 邮箱
	 * @param memberId 过滤掉自己的ID
	 * @return
	 */
	public Member findByEmailIgnoreId(String email, Long memberId) {
		return MemberMapper.findByEmailIgnoreId(email, memberId);
	}
	
	/**
	 * 绑定会员卡
	 * @param memberId 会员ID
	 * @param memberCardCode 会员卡号
	 */
	@Transactional
	@Override
	public void bingMemberCard(Long memberId, String memberCardCode) {
		if (memberId == null || memberCardCode == null) {
			throw new RuntimeException("参数错误");
		}
		Member member = this.findMemberByMemberId(memberId);
		if (member != null) {
			MemberCard memberCard = memberCardService.findMemberCardByCode(memberCardCode);
			if (memberCard != null) {
				if (memberCard.getMemberId() != null) {
					throw new RuntimeException("该会员卡已被其他用户绑定");
				}
				
				if (member.getCardId() != null) {
					throw new RuntimeException("该会员已绑定其他会员卡");
				}
				
				member.setCardId(memberCard.getMemberCardId());//会员关联会员卡
				this.updateMember(member);
				
				memberCard.setMemberId(member.getMemberId());//会员卡关联会员
				memberCard.setBindTime(new Date());
				memberCard.setIsValid(false);			
				memberCardService.updateMemberCard(memberCard);
			} else {
				throw new RuntimeException("会员卡不存在");
			}
		} else {
			throw new RuntimeException("会员不存在");
		}
	}
	
	public int unbind(Long memberId) {
		return MemberMapper.unbind(memberId);
	}
	
	/**
	 * 根据用户名称查找用户
	 * @param memberName 用户名
	 * @return
	 */
	public Member findMemberByName(String memberName) {
		return MemberMapper.findMemberByName(memberName);				
	}
}
